using System;
using System.Net;
using System.Web;
using AUSRIS.Framework.Logging;

namespace AUSRIS.Reports.Extensions.Security.Authentication
{
    internal sealed class CookieUtility
    {
        private static string customAuthCookieName;
        private static object lockObject = new object();

        internal static string CustomAuthCookieName
        {
            get
            {
                lock(lockObject)
                {
                    return customAuthCookieName;
                }
            }
            set
            {
                lock(lockObject)
                {
                    customAuthCookieName = value;
                }
#if DEBUG
				Log.Debug(Log.GetSource(), value);
#endif
            }
        }

        internal static Cookie TranslateToCookie(HttpCookie httpCookie)
        {
            if(httpCookie == null)
            {
                return null;
            }
            else
            {
                Cookie cookie = new Cookie(httpCookie.Name, httpCookie.Value);
                if(httpCookie.Domain == null)
                {
                    cookie.Domain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
                }
                cookie.Expires = httpCookie.Expires;
                cookie.Path = httpCookie.Path;
                cookie.Secure = httpCookie.Secure;
                return cookie;
            }
        }

        internal static void RelayCookieToClient(Cookie cookie)
        {
            if(HttpContext.Current.Response.Cookies[cookie.Name] == null)
            {
                HttpContext.Current.Response.Cookies.Remove(cookie.Name);
            }
            HttpContext.Current.Response.SetCookie(TranslateToHttpCookie(cookie));
#if DEBUG
			Log.Debug(Log.GetSource(), cookie.Value);
#endif
        }



        private static HttpCookie TranslateToHttpCookie(Cookie cookie)
        {
            if(cookie == null)
            {
                return null;
            }
            HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Value);
            // Add domain only if it is dotted (IE doesn't send back the cookie if we set the domain otherwise)
            if(cookie.Domain.IndexOf('.') != -1)
            {
                httpCookie.Domain = cookie.Domain;
            }
            httpCookie.Expires = cookie.Expires;
            httpCookie.Path = cookie.Path;
            httpCookie.Secure = cookie.Secure;
            return httpCookie;
        }
    }
}
